package com.ebelter.myehc.models.http.upload;

import android.os.Message;
import android.text.TextUtils;
import com.ebelter.btcomlib.common.Constants;
import com.ebelter.btcomlib.models.beans.ScaleUser;
import com.ebelter.btcomlib.models.bluetooth.products.bloodoxgen.bean.BOMesureResultBean;
import com.ebelter.btcomlib.models.bluetooth.products.bloodoxgen.bean.BOMesureResultBean_Table;
import com.ebelter.btcomlib.models.bluetooth.products.bpm.bean.BpmMesureResult;
import com.ebelter.btcomlib.models.bluetooth.products.bpm.bean.BpmMesureResult_Table;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.BraceletConstant;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.BraDb;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.BraDb_Table;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.RateBean;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.SleepArrayInfo;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.WalkBean;
import com.ebelter.btcomlib.models.bluetooth.products.ear_temperature.bean.EarTemMesureResult;
import com.ebelter.btcomlib.models.bluetooth.products.ear_temperature.bean.EarTemMesureResult_Table;
import com.ebelter.btcomlib.models.bluetooth.products.scale.bean.ScaleMeasureResult;
import com.ebelter.btcomlib.models.bluetooth.products.scale.bean.ScaleMeasureResult_Table;
import com.ebelter.btcomlib.models.bluetooth.products.three2one.bean.ThreeOneMesureResultBean;
import com.ebelter.btcomlib.models.bluetooth.products.three2one.bean.ThreeOneMesureResultBean_Table;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.models.https.responses.BaseResponse;
import com.ebelter.btcomlib.utils.BaseHandle;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.ThreadManager;
import com.ebelter.btcomlib.utils.TimeUtils;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.myehc.models.http.request.EhcNetUtils;
import com.raizlabs.android.dbflow.sql.language.Select;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 上传工具
 */

public class UpLoadUtil extends BaseHandle {


    public static final String TAG = "UpLoadUtil";

    private static final int what_check = 1;

    private static final int what_braCheck = 2;

    private UpLoadUtil() {
        ehcNetUtils = EhcNetUtils.getInstance();
    }


    private static UpLoadUtil instance;

    public static UpLoadUtil getInstance() {
        if (instance == null) {
            synchronized (UpLoadUtil.class) {
                if (instance == null) instance = new UpLoadUtil();
            }
        }
        return instance;
    }

    private EhcNetUtils ehcNetUtils;


    @Override
    public void handleMsg(Message msg) {
        super.handleMsg(msg);

        if (msg.what == what_check) {
            startCheck();
        } else if (msg.what == what_braCheck) {
            upLoadBraData();
        }
    }


    private void startCheck() {

        removeMessages(what_check);
        sendEmptyMessageDelayed(what_check, 5000);

        ThreadManager.getShortPool().execute(new Runnable() {
            @Override
            public void run() {
                String authKey = UserSpUtil.readString(Constants.IUser.AUTH_KEY, "");
                if (TextUtils.isEmpty(authKey)) {
                    LogUtils.i(TAG, "检测到未登录状态");
                    return;
                }

                LogUtils.i(TAG, "UpLoadUtil---检测缓存的数据");

                BpmMesureResult bpmMesureResult = new Select().from(BpmMesureResult.class).where(BpmMesureResult_Table.authKey.eq(authKey)).querySingle();
                if (bpmMesureResult != null) {
                    upLoadBloodPressure(false, bpmMesureResult);
                }

                BOMesureResultBean bo = new Select().from(BOMesureResultBean.class).where(BOMesureResultBean_Table.authKey.eq(authKey)).querySingle();
                if (bo != null) {
                    upLoadBO(false, bo);
                }

                EarTemMesureResult ear = new Select().from(EarTemMesureResult.class).where(EarTemMesureResult_Table.authKey.eq(authKey)).querySingle();
                if (ear != null) {
                    upLoadEarTem(false, ear);
                }

                ThreeOneMesureResultBean threeOne = new Select().from(ThreeOneMesureResultBean.class).where(ThreeOneMesureResultBean_Table.authKey.eq(authKey)).querySingle();
                if (threeOne != null) {
                    upLoadThreeOne(false, threeOne);
                }

                ScaleMeasureResult scale = new Select().from(ScaleMeasureResult.class).where(ScaleMeasureResult_Table.authKey.eq(authKey)).querySingle();
                if (scale != null) {
                    upLoadScale(false, scale);
                }

            }
        });


    }


    private List<String> bp_uploadTime = new ArrayList<>();

    public void upLoadBloodPressure(final boolean isNewData, final BpmMesureResult bpm) {
        if (bpm == null) return;

        LogUtils.i(TAG, "上传血压--" + bpm);
        String authKey = bpm.authKey;
        if (TextUtils.isEmpty(authKey)) return;
        final String time = bpm.testTime;
        boolean contains = bp_uploadTime.contains(time);
        if (contains) {
            return;
        } else {
            bp_uploadTime.add(time);
        }
        ehcNetUtils.upLoadBloodPressure(this, authKey, bpm.systolicPressure, bpm.diastolicPressure, bpm.pulse, time, new HttpResponse<BaseResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, BaseResponse baseResponse, String s) {
                bp_uploadTime.remove(time);
                if (isRequestSuccess && baseResponse.resultCode == 1) {
                    //表明上传成功
                    if (!isNewData) {
                        bpm.delete();
                    }
                    LogUtils.i(TAG, "UpLoadUtil------血压---上传成功" + bpm);
                } else {
                    //上传失败
                    if (isNewData) {
                        bpm.save();
                    }
                    LogUtils.i(TAG, "UpLoadUtil------血压---上传失败" + bpm);
                }
            }
        });
    }


    private List<String> bo_uploadTime = new ArrayList<>();

    public void upLoadBO(final boolean isNewData, final BOMesureResultBean bo) {
        if (bo == null) return;
        String authKey = bo.authKey;
        if (TextUtils.isEmpty(authKey)) return;
        final String time = bo.mesureTimeStr;
        boolean contains = bo_uploadTime.contains(time);
        if (contains) {
            return;
        } else {
            bo_uploadTime.add(time);
        }

        ehcNetUtils.upLoadBloodOxygen(this, authKey, bo.bloodOxygen, bo.pulse, time, new HttpResponse<BaseResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, BaseResponse baseResponse, String s) {
                bo_uploadTime.remove(time);
                if (isRequestSuccess && baseResponse.resultCode == 1) {
                    //表明上传成功
                    if (!isNewData) {
                        bo.delete();
                    }
                    LogUtils.i(TAG, "UpLoadUtil------血氧---上传成功" + bo);
                } else {
                    //上传失败
                    if (isNewData) {
                        bo.save();
                    }
                    LogUtils.i(TAG, "UpLoadUtil------血氧---上传失败" + bo);
                }
            }
        });
    }


    private List<String> earTem_uploadTime = new ArrayList<>();

    public void upLoadEarTem(final boolean isNewData, final EarTemMesureResult ear) {
        if (ear == null) return;
        String authKey = ear.authKey;
        if (TextUtils.isEmpty(authKey)) return;
        final String time = ear.measureTimeStr;
        boolean contains = earTem_uploadTime.contains(time);
        if (contains) {
            return;
        } else {
            earTem_uploadTime.add(time);
        }

        ehcNetUtils.upLoadTemperature(this, authKey, ear.temperature, time, new HttpResponse<BaseResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, BaseResponse baseResponse, String s) {
                earTem_uploadTime.remove(time);
                if (isRequestSuccess && baseResponse.resultCode == 1) {
                    if (!isNewData) {//表明上传成功
                        ear.delete();
                    }
                    LogUtils.i(TAG, "UpLoadUtil------体温枪---上传成功" + ear);
                } else {
                    if (isNewData) {//上传失败
                        ear.save();
                    }
                    LogUtils.i(TAG, "UpLoadUtil------体温枪---上传失败" + ear);
                }
            }
        });
    }


    private List<String> earScale_uploadTime = new ArrayList<>();

    public void upLoadScale(final boolean isNewData, final ScaleMeasureResult scale) {
        if (scale == null) return;
        String authKey = scale.authKey;
        if (TextUtils.isEmpty(authKey)) return;
        final String time = scale.measureTime;
        boolean contains = earScale_uploadTime.contains(time);
        if (contains) {
            return;
        } else {
            earScale_uploadTime.add(time);
        }

        //authKey,weight,adiposerate,moisture,basalMetabolism,visceralfat,muscle,bone,bmi,protein,time
        ehcNetUtils.upLoadBodyComposition(this, authKey, scale.weight, scale.fat,
                scale.waterRate, (int) scale.bmr, scale.visceralFat, scale.muscleVolume,
                scale.boneVolume, scale.bmi, scale.protein, time, new HttpResponse<BaseResponse>() {
                    @Override
                    public void result(boolean isRequestSuccess, String requestDes, BaseResponse baseResponse, String s) {
                        earScale_uploadTime.remove(time);
                        if (isRequestSuccess && baseResponse.resultCode == 1) {
                            //表明上传成功
                            if (!isNewData) {
                                scale.delete();
                            }
                            LogUtils.i(TAG, "UpLoadUtil------体脂秤---上传成功" + scale);
                        } else {
                            //上传失败
                            if (isNewData) {
                                scale.save();
                            }
                            LogUtils.i(TAG, "UpLoadUtil------体脂秤---上传失败" + scale);
                        }
                    }
                });
    }


    private List<String> threeOne_uploadTime = new ArrayList<>();

    public void upLoadThreeOne(final boolean isNewData, final ThreeOneMesureResultBean threeOne) {
        if (threeOne == null) return;
        String authKey = threeOne.authKey;
        if (TextUtils.isEmpty(authKey)) return;
        final String time = threeOne.mesureTimeStr;
        boolean contains = threeOne_uploadTime.contains(time);
        if (contains) {
            return;
        } else {
            threeOne_uploadTime.add(time);
        }

        //01血糖 02尿酸 03胆固醇
        if (threeOne.product == 1) {
            ehcNetUtils.upLoadBloodSugar(this, authKey, threeOne.mesureValue, threeOne.type, time, new HttpResponse<BaseResponse>() {
                @Override
                public void result(boolean isRequestSuccess, String requestDes, BaseResponse baseResponse, String s) {
                    threeOne_uploadTime.remove(time);
                    if (isRequestSuccess && baseResponse.resultCode == 1) {
                        //表明上传成功
                        if (!isNewData) {
                            threeOne.delete();
                        }
                        LogUtils.i(TAG, "UpLoadUtil------三合一---血糖上传成功" + threeOne);
                    } else {
                        //上传失败
                        if (isNewData) {
                            threeOne.save();
                        }
                        LogUtils.i(TAG, "UpLoadUtil------三合一---血糖上传失败" + threeOne);
                    }
                }
            });

        } else if (threeOne.product == 2) {
            ehcNetUtils.upLoadUa(this, authKey, (int) threeOne.mesureValue, time, new HttpResponse<BaseResponse>() {
                @Override
                public void result(boolean isRequestSuccess, String requestDes, BaseResponse baseResponse, String s) {
                    threeOne_uploadTime.remove(time);
                    if (isRequestSuccess && baseResponse.resultCode == 1) {
                        //表明上传成功
                        if (!isNewData) {
                            threeOne.delete();
                        }
                        LogUtils.i(TAG, "UpLoadUtil------三合一---尿酸上传成功" + threeOne);
                    } else {
                        //上传失败
                        if (isNewData) {
                            threeOne.save();
                        }
                        LogUtils.i(TAG, "UpLoadUtil------三合一---尿酸上传失败" + threeOne);
                    }
                }
            });

        } else if (threeOne.product == 3) {
            ehcNetUtils.upLoadCholesterol(this, authKey, threeOne.mesureValue, time, new HttpResponse<BaseResponse>() {
                @Override
                public void result(boolean isRequestSuccess, String requestDes, BaseResponse baseResponse, String s) {
                    threeOne_uploadTime.remove(time);
                    if (isRequestSuccess && baseResponse.resultCode == 1) {
                        //表明上传成功
                        if (!isNewData) {
                            threeOne.delete();
                        }
                        LogUtils.i(TAG, "UpLoadUtil------三合一---胆固醇上传成功" + threeOne);
                    } else {
                        //上传失败
                        if (isNewData) {
                            threeOne.save();
                        }
                        LogUtils.i(TAG, "UpLoadUtil------三合一---胆固醇上传失败" + threeOne);
                    }
                }
            });

        }


    }


    private static final String BraUploadSuccessTAG1 = "BraUploadSuccessTAG1";
    private static final String BraUploadSuccessTAG2 = "BraUploadSuccessTAG2";
    private static final String BraUploadSuccessTAG3 = "BraUploadSuccessTAG3";
    private boolean braUploadSuccess1;
    private boolean braUploadSuccess2;
    private boolean braUploadSuccess3;
    private List<WalkBean> upWalkBeans;
    private List<RateBean> upRateBeans;
    private List<SleepArrayInfo> upSleepArrayInfos;


    //开始上传手环数据 只要同步完手环就会到这里调用一次
    public void startUpLoadBraData() {
        LogUtils.i(TAG, "--------------------开始上传了手环数据");
       // removeMessages(what_braCheck);
        braUploadSuccess1 = false;//先置为上传失败
        braUploadSuccess2 = false;//先置为上传失败
        braUploadSuccess3 = false;//先置为上传失败
        ehcNetUtils.cancelTag(BraUploadSuccessTAG1);
        ehcNetUtils.cancelTag(BraUploadSuccessTAG2);
        ehcNetUtils.cancelTag(BraUploadSuccessTAG3);
        upWalkBeans = null;
        upRateBeans = null;
        upSleepArrayInfos = null;
       // sendEmptyMessage(what_braCheck);

        upLoadBraData();
    }

    private void upLoadBraData() {
        if (braUploadSuccess1 && braUploadSuccess2 && braUploadSuccess3) {
            //说明已经上传成功了
            removeMessages(what_braCheck);
            LogUtils.i(TAG, "手环数据 braUploadSuccess s = true 说明已经上传成功了");
            return;
        } else {
            sendEmptyMessageDelayed(what_braCheck, 10000);//10秒后再去检查一遍的意思
        }

        if (!NetUtils.available()) {
            LogUtils.i(TAG, "手环数据因为网络不可用 这次上传失败");
            return;
        }
        String authKey = UserSpUtil.readString(Constants.IUser.AUTH_KEY, "");
        if (TextUtils.isEmpty(authKey)) {
            LogUtils.i(TAG, "手环数据因为检测到未登录状态 这次上传失败");
            return;
        }

        if (!braUploadSuccess1 && !braUploadSuccess2 && !braUploadSuccess3 && upWalkBeans == null && upRateBeans == null && upSleepArrayInfos == null) {
            //三个状态都是false 说明三个都还没上传成功
            LogUtils.i(TAG, "三个状态都是false 说明三个都还没上传成功 走一遍查询");
            braQuery();//走一遍查询
        } else {


            if (!braUploadSuccess1 && upWalkBeans != null && upWalkBeans.size() > 0) {
                //上传步数
                LogUtils.i(TAG, "上传步数卡路里距离"+upWalkBeans);
                ehcNetUtils.upLoadStepsDistanceCariliLv(BraUploadSuccessTAG1, authKey, upWalkBeans, new HttpResponse<BaseResponse>() {
                    @Override
                    public void result(boolean isRequestSuccess, String requestDes, BaseResponse baseResponse, String s) {
                        if (isRequestSuccess && baseResponse.resultCode == 1) {
                            LogUtils.i(TAG, "上传步数卡路里距离---成功");
                            braUploadSuccess1 = true;
                            upWalkBeans = null;
                        } else {
                            LogUtils.i(TAG, "上传步数卡路里距离---失败");
                        }
                    }
                });
            }else {
                LogUtils.i(TAG, "步数卡路里距离 没有数据 不用上传");
            }

            if (!braUploadSuccess2 && upRateBeans != null && upRateBeans.size() > 0) {
                //上传心率
                LogUtils.i(TAG, "上传心率"+upRateBeans);
                ehcNetUtils.upLoadXinLv(BraUploadSuccessTAG2, authKey, upRateBeans, new HttpResponse<BaseResponse>() {
                    @Override
                    public void result(boolean isRequestSuccess, String requestDes, BaseResponse baseResponse, String s) {
                        if (isRequestSuccess && baseResponse.resultCode == 1) {
                            LogUtils.i(TAG, "上传心率---成功");
                            braUploadSuccess2 = true;
                            upRateBeans = null;
                        } else {
                            LogUtils.i(TAG, "上传心率---失败");
                        }
                    }
                });
            }else {
                LogUtils.i(TAG, "心率 没有数据 不用上传");
            }

            if (!braUploadSuccess3 && upSleepArrayInfos != null && upSleepArrayInfos.size() > 0) {
                //上传睡眠
                LogUtils.i(TAG, "上传睡眠"+upSleepArrayInfos);
                ehcNetUtils.upLoadShuiMian(BraUploadSuccessTAG3, authKey, upSleepArrayInfos, new HttpResponse<BaseResponse>() {
                    @Override
                    public void result(boolean isRequestSuccess, String requestDes, BaseResponse baseResponse, String s) {
                        if (isRequestSuccess && baseResponse.resultCode == 1) {
                            LogUtils.i(TAG, "上传睡眠---成功");
                            braUploadSuccess3 = true;
                            upSleepArrayInfos = null;
                        } else {
                            LogUtils.i(TAG, "上传睡眠---失败");
                        }
                    }
                });
            }else {
                LogUtils.i(TAG, "睡眠 没有数据 不用上传");
            }

        }


    }

    private void braQuery() {
        ThreadManager.getShortPool().execute(new Runnable() {
            @Override
            public void run() {


                long cT = System.currentTimeMillis();

                String today = TimeUtils.formatTime14(cT);//yyMMdd  今天181022


                long newestHeartTimeLong = UserSpUtil.readLong(BraceletConstant.B_NEWEST_HEART_TIME_L);//取到最近上传的时间
                String newestHeartTimeStr = UserSpUtil.readString(BraceletConstant.B_NEWEST_HEART_TIME_STR);

                LogUtils.i(TAG, "--UpLoadUtil--newestHeartTimeLong=" + newestHeartTimeLong + "---newestHeartTimeStr=" + newestHeartTimeStr);


                long tianqian_1Time =  TimeUtils.parseFormatter1Time(TimeUtils.formatTime3(cT-1*86400000)+" 00:00:00").getTime();//昨天天的0点0分0秒的时间戳

                if (newestHeartTimeLong>tianqian_1Time){
                    newestHeartTimeLong=tianqian_1Time;
                    LogUtils.i(TAG, "最新心跳时间大于今天的0点0分0秒的时间 开始时间采用了0点0分时间 = "+TimeUtils.formatTime1(newestHeartTimeLong));

                }


                String startday = TimeUtils.formatter15Time(newestHeartTimeLong)+"00";//yyMMdd  昨天1810210110  yyMMddHH


                long startStr = Long.parseLong(startday);//1810210000
                long endStr = Long.parseLong(today + "2350");//1810222350

                if (startStr >= endStr) {
                    LogUtils.i(TAG, "解析出来的时间不对yesterDaystartStr=" + startStr + "---endStr=" + endStr);
                    return;
                }

                //查询到开始和结束的所有数据
                List<BraDb> dbList = new Select().from(BraDb.class)
                        .where(BraDb_Table.timeStr.greaterThanOrEq(startStr))
                        .and(BraDb_Table.timeStr.lessThanOrEq(endStr))
                        .orderBy(BraDb_Table.timeStr, true).queryList();

                if (dbList.size() == 0) {
                    LogUtils.i(TAG, "手环数据查询为空上传失败");
                    return;
                }


                Map<String, Integer> stepsMap = new HashMap<>();//步数


                List<String> stepskeys = new ArrayList<>();

                List<WalkBean> walkBeans = new ArrayList<>();
                List<RateBean> rateBeans = new ArrayList<>();
                List<SleepArrayInfo> sleepArrayInfos = new ArrayList<>();//睡眠


                List<BraDb> yesterdayTodayShMList = new ArrayList<>();//昨天和今天的睡眠数据集合

                ScaleUser user = ScaleUser.getUser();
                float stride = (float) (((user.getSex() == 1 ? user.getHeight() * 0.413 : user.getHeight() * 0.415) * 1.0 / 100));//这样做是为了取最新的步幅 m
                int weight2 = NumUtils.numBaoLiuWei0(user.getWeight() - 15);
                float stepCaruli = NumUtils.numBaoLiuWei6(weight2 * 0.000693 + 0.005895);//取最新的每步消耗的卡路里 此时的单位是kcal
                if (stepCaruli<0){
                    stepCaruli=0;
                }



                for (BraDb braDb : dbList) {
                    LogUtils.i(TAG, "手环准备上传 - " + braDb.toString());

                    Date date = TimeUtils.parseFormatter15Time(braDb.timeStr + "");//当前项的记录时间 yyMMddHHmm
                    long time = date.getTime();
                    // int h = Integer.parseInt(TimeUtils.formatTime16(time));//0-23




                    //  if (braDb.dateType == 0x01) { //计步数据
                    String stepkey = (braDb.timeStr + "").substring(0, 8);//yyMMddHH 按照时间轴来做搜索的key

                    //统计步数
                    if (stepsMap.containsKey(stepkey)) {//可能同一时间的key
                        stepsMap.put(stepkey, stepsMap.get(stepkey) + braDb.step);
                    } else {
                        stepsMap.put(stepkey, braDb.step);
                        stepskeys.add(stepkey);
                    }


                    //--------------------------------------------------------------------心率01

                    if (braDb.heart > 0) {
                        RateBean rateBean = new RateBean(time, braDb.heart);
                        rateBeans.add(rateBean);
                    }

                    if (braDb.heart1 > 0) {
                        RateBean rateBean = new RateBean(time + 150000, braDb.heart1);
                        rateBeans.add(rateBean);
                    }
                    if (braDb.heart2 > 0) {
                        RateBean rateBean = new RateBean(time + 300000, braDb.heart2);
                        rateBeans.add(rateBean);
                    }

                    if (braDb.heart3 > 0) {
                        RateBean rateBean = new RateBean(time + 450000, braDb.heart3);
                        rateBeans.add(rateBean);
                    }

                    //--------------------------------------------------------------------心率02

                    //睡眠状况 0清醒 1深睡 2浅睡
                    //睡眠数据
                    //0x01 为记步数据 0x10 为睡眠数据（0x11 为开始睡眠 0x12 为清醒状态 0x13 为浅睡状态 0x14 为深睡状态 0x15 为结束睡眠）
                    if (braDb.dateType == 0x11 || braDb.dateType == 0x15 || braDb.dateType == 0x12 || braDb.dateType == 0x13 || braDb.dateType == 0x14) {
                        yesterdayTodayShMList.add(braDb);//把开始和结束的所有数据有关睡眠的先放在集合里面
                    }


                }


                for (String key : stepskeys) {//---------------01统计好步数 距离 卡路里
                    if (stepsMap.containsKey(key)) {
                        int hourSteps = stepsMap.get(key);

                        if (hourSteps > 0) {
                            float hourDis = (stride * hourSteps);//m
                            float hourCar = stepCaruli * hourSteps;//kcal

                            WalkBean walkBean = new WalkBean();
                            walkBean.setTimeLong(TimeUtils.parseFormatter17Time(key).getTime());//解析时间
                            walkBean.houreSteps = hourSteps;
                            walkBean.houreDistance = NumUtils.numBaoLiuWei2_down((float) (hourDis * 1.0 / 1000));//把米单位换成km的
                            walkBean.houreCalories = NumUtils.numBaoLiuWei2_down(hourCar);
                            walkBeans.add(walkBean);
                            LogUtils.i(TAG, "加入的是 hourCar = " + hourCar + "------" + walkBean.toString());
                        }
                    }
                }


                //----------------统计好昨天和今天的所有睡眠数据
                long ctt=System.currentTimeMillis();
                LogUtils.i(TAG," 开始 计算睡眠的归属时间 = "+TimeUtils.formatTime1(ctt));
                for (int w = 0; w < yesterdayTodayShMList.size(); w++) {
                    fiilAffiliationDate(w, yesterdayTodayShMList);
                }
                long ctt2=System.currentTimeMillis();
                LogUtils.i(TAG," 结束 计算睡眠的归属时间 = "+TimeUtils.formatTime1(ctt2)+"---总用时毫秒数="+(ctt2-ctt));

                for (int e = 0; e < yesterdayTodayShMList.size(); e++) {
                    BraDb braDb = yesterdayTodayShMList.get(e);
                    Date date = TimeUtils.parseFormatter15Time(braDb.timeStr + "");//当前项的记录时间 yyMMddHHmm
                    long time = date.getTime();
                    long sleepEndTime = time + 600000;

                    String st = TimeUtils.formatTime1(time);
                    String et = TimeUtils.formatTime1(sleepEndTime);


                    SleepArrayInfo sleepArrayInfo = null;

                    if (braDb.dateType == 0x11 || braDb.dateType == 0x15 || braDb.dateType == 0x12) {//0x11 为开始睡眠  0x15 为结束睡眠  0x12 清醒状态

                        sleepArrayInfo = new SleepArrayInfo(st, et, 0 + "", st, braDb.affiliationDate);//0为清醒 2浅眠 1深眠

                    } else if (braDb.dateType == 0x13) {// 0x13 为浅睡状态

                        sleepArrayInfo = new SleepArrayInfo(st, et, 2 + "", st, braDb.affiliationDate);

                    } else if (braDb.dateType == 0x14) {//0x14 为深睡状态

                        sleepArrayInfo = new SleepArrayInfo(st, et, 1 + "", st, braDb.affiliationDate);
                    }

                    sleepArrayInfos.add(sleepArrayInfo);
                }


                upWalkBeans = walkBeans;
                upRateBeans = rateBeans;
                upSleepArrayInfos = sleepArrayInfos;

                removeMessages(what_braCheck);
                sendEmptyMessage(what_braCheck);
            }
        });


    }

    //计算当前的睡眠的归属日期
    private void fiilAffiliationDate(int w, List<BraDb> yesterdayTodayShMList) {
        BraDb currentBraDb = yesterdayTodayShMList.get(w);


        Date currentdate = TimeUtils.parseFormatter15Time(currentBraDb.timeStr + "");//当前项的记录时间 yyMMddHHmm
        String currentItemTime = TimeUtils.formatTime3(currentdate.getTime());//yyyy-MM-dd

        //0x01 为记步数据 0x10 为睡眠数据（0x11 为开始睡眠 0x12 为清醒状态 0x13 为浅睡状态 0x14 为深睡状态 0x15 为结束睡眠）
        if (currentBraDb.dateType == 0x15) {
            currentBraDb.affiliationDate = currentItemTime;//如果是结束睡眠是今天 那么今天的睡眠的也是属于今天的
            currentBraDb.update();
            return;
        }


        BraDb targetBraDb = null;
        int queryNextIndex = w + 1;

        for (int i = queryNextIndex; i < yesterdayTodayShMList.size(); i++) {
            BraDb braDb = yesterdayTodayShMList.get(i);//查询后面的时间是否到了结束时间  这一步循环语句是为了查找到下一个结束睡眠的目标
            if (braDb.dateType == 0x15) {//0x15 为结束睡眠
                targetBraDb = braDb;
                break;
            }
        }

        if (targetBraDb == null) {
            //说明在当前项后面没有找到结束睡眠的记录数据 那就当前项的睡眠归属日期写成当天的
            currentBraDb.affiliationDate = currentItemTime;
            currentBraDb.update();
        } else {
            //如果找到了目标时间 就把当前的睡眠时间归属到那天的
            Date targetdate = TimeUtils.parseFormatter15Time(targetBraDb.timeStr + "");//时间 yyMMddHHmm
            String targetItemTime = TimeUtils.formatTime3(targetdate.getTime());//yyyy-MM-dd

            currentBraDb.affiliationDate = targetItemTime;
            currentBraDb.update();

        }


    }
}
